import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// 引入路由
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // 设置axios请求的基础的基础地址
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    // 如果当前存有token,就加在请求头上
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data
    if (res.success) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'success',
    //     duration: 5 * 1000
    //   })
      return res
    } else {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(new Error(res.message))
    }
  },
  async error => {
    console.log('err' + error) // for debug
    console.log(error.response.data.code)
    if (error.response.data.code === 10002) {
      console.log('token失效了')
      await store.dispatch('user/userLogout')
      router.push(`/login?return_url=${encodeURIComponent(this.$route.fullPath)}`)
    }
    return Promise.reject(error)
  }
)

export default service
